
package com.ys.service.account.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ys.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.account.TcwAdvanceAccount;
import com.ys.entity.account.TcwAdvanceAccountDetail;
import com.ys.entity.account.TcwAdvanceAccountReimbursement;
import com.ys.entity.account.TcwAdvanceAccountReimbursementItem;
import com.ys.entity.business.TbBaseInfo;
import com.ys.entity.finance.TcwPartnerBankInfo;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.entity.sys.TsUserBankInfo;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.finance.TcwFinancialTransactionFlowEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.account.AccountMapper;
import com.ys.mapper.account.TcwAdvanceAccountDetailMapper;
import com.ys.mapper.account.TcwAdvanceAccountReimbursementItemMapper;
import com.ys.mapper.account.TcwAdvanceAccountReimbursementMapper;
import com.ys.service.account.TcwAdvanceAccountDetailService;
import com.ys.service.account.TcwAdvanceAccountReimbursementService;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwFinancialTransactionFlowService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

/**
 * 预支账户报销单
 */
@Service("tcwAdvanceAccountReimbursement")
public class TcwAdvanceAccountReimbursementServiceImpl implements TcwAdvanceAccountReimbursementService {
	private static final Logger logger = LoggerFactory.getLogger(TcwAdvanceAccountReimbursementServiceImpl.class);

	@Autowired
	private TcwAdvanceAccountReimbursementMapper tcwAdvanceAccountReimbursementMapper;

	@Autowired
	private TcwAdvanceAccountReimbursementItemMapper tcwAdvanceAccountReimbursementItemMapper;

    @Autowired
    private TcwAdvanceAccountDetailMapper tcwAdvanceAccountDetailMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;

	@Autowired
	private TcwAdvanceAccountDetailService tcwAdvanceAccountDetailService;

	@Autowired
	private TcwFinancialTransactionFlowService tcwFinancialTransactionFlowService;

	/**
	 * 新增
	 */
	@Override
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcwAdvanceAccountReimbursement tcwAdvanceAccountReimbursement = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccountReimbursement.class);
		tcwAdvanceAccountReimbursement.setStatus(1);//状态
		tcwAdvanceAccountReimbursement.setEffectStock(0);//审批状态

		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			tcwAdvanceAccountReimbursement.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}

		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			//验证详情信息
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			if(subData!=null && subData.size()>0){
				String errorBackByItem = null;//错误信息
				for (int i = 0; i < subData.size(); i++) {
					JSONObject jSONObject = subData.getJSONObject(i);
					Map<String, Object> paramsNewByRecord = new HashMap<>();
					if(jSONObject.get("reimbursementItemId")!=null && !"".equals(jSONObject.get("reimbursementItemId")))paramsNewByRecord.put("id",jSONObject.get("reimbursementItemId"));//id
					if(jSONObject.get("advanceAccountDetailId")!=null && !"".equals(jSONObject.get("advanceAccountDetailId"))){
						paramsNewByRecord.put("advanceAccountDetailId",jSONObject.get("advanceAccountDetailId"));//预支账户管理明细表id
					}else {
						errorBackByItem = "第"+(i+1)+"行的明细信息为空！";
					}
					paramsNewByRecord.put("pbid",tcwAdvanceAccountReimbursement.getBid());//bid
					if(jSONObject.get("annexFile")!=null && !"".equals(jSONObject.get("annexFile"))){
						paramsNewByRecord.put("annexFile",jSONObject.get("annexFile"));//附件
					}
					paramsNewByItem.add(paramsNewByRecord);
				}
				if(errorBackByItem!=null && !"".equals(errorBackByItem)){
					return R.error(errorBackByItem);
				}
			}else {
				return R.error("列表信息为空！");
			}
		}else {
			return R.error("列表信息为空！");
		}

		//新增列表信息
		//先删除
		accountMapper.deleteAdvanceAccountReimbursementByPbid(tcwAdvanceAccountReimbursement.getBid());
		for (int i = 0; i < paramsNewByItem.size(); i++) {
			Map<String, Object> item = paramsNewByItem.get(i);
			TcwAdvanceAccountReimbursementItem tcwAdvanceAccountReimbursementItem = JSON.parseObject(JSON.toJSONString(item), TcwAdvanceAccountReimbursementItem.class);
			tcwAdvanceAccountReimbursementItem.setStatus(1);
			//新增列表
			tcwAdvanceAccountReimbursementItemMapper.insert(tcwAdvanceAccountReimbursementItem);
			//更新明细的附件信息
			if(item.get("annexFile")!=null && !"".equals(item.get("annexFile"))){
				TcwAdvanceAccountDetail tcwAdvanceAccountDetail = new TcwAdvanceAccountDetail();
				tcwAdvanceAccountDetail.setId(tcwAdvanceAccountReimbursementItem.getAdvanceAccountDetailId());
				tcwAdvanceAccountDetail.setAnnexFile(item.get("annexFile").toString());
				tcwAdvanceAccountDetailMapper.update(tcwAdvanceAccountDetail);
			}
		}

		//新增
		tcwAdvanceAccountReimbursementMapper.insert(tcwAdvanceAccountReimbursement);

		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, tcwAdvanceAccountReimbursement.getBid(), createUserId);
			yspTaskService.setOtherParams(tcwAdvanceAccountReimbursement.getBid(),tcwAdvanceAccountReimbursement.getRemark(),params.get("vname"));
		}
		//return R.ok(EditDto.closeAndReload());
		return R.ok(AddDto.gotoEdit("/web/account/tcwAdvanceAccountReimbursement/toEdit?bid=" + tcwAdvanceAccountReimbursement.getBid()));
	}

	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TcwAdvanceAccountReimbursement tcwAdvanceAccountReimbursement = JSON.parseObject(JSON.toJSONString(params), TcwAdvanceAccountReimbursement.class);
		// 验证状态
		YsProcInst ysProcInst = new YsProcInst().setBid(tcwAdvanceAccountReimbursement.getBid()).queryFirst();
		if (ysProcInst == null) {
			return R.error("审批数据不存在，无法编辑");
		} else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("已流转，无法编辑");
		}

		//列表信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			//验证详情信息
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			String errorBackByItem = null;//错误信息
			String fistJylx = "";
			boolean jylxIsSame = true;
			if(subData!=null && subData.size()>0){
				for (int i = 0; i < subData.size(); i++) {
					JSONObject jSONObject = subData.getJSONObject(i);
					Map<String, Object> paramsNewByRecord = new HashMap<>();
					if(jSONObject.get("reimbursementItemId")!=null && !"".equals(jSONObject.get("reimbursementItemId")))paramsNewByRecord.put("id",jSONObject.get("reimbursementItemId"));//id
					if(jSONObject.get("advanceAccountDetailId")!=null && !"".equals(jSONObject.get("advanceAccountDetailId"))){
						paramsNewByRecord.put("advanceAccountDetailId",jSONObject.get("advanceAccountDetailId"));//预支账户管理明细表id
					}else {
						errorBackByItem = "第"+(i+1)+"行的明细信息为空！";
					}
					TcwAdvanceAccountDetail fromDetail = new TcwAdvanceAccountDetail().setId(Long.parseLong(jSONObject.get("reimbursementItemId").toString())).queryFirst();
					if(fromDetail!=null){
						if(i==0){
							fistJylx = fromDetail.getVjylx();
						}else {
							if(!fistJylx.equals(fromDetail.getVjylx())){
								jylxIsSame = false;
							}
						}
						if(!fromDetail.getCompanyInfoVid().equals(tcwAdvanceAccountReimbursement.getCompanyVid())){
							errorBackByItem = "第"+(i+1)+"行的所属公司信息不一致！";
						}
					}
					paramsNewByRecord.put("pbid",tcwAdvanceAccountReimbursement.getBid());//bid
					paramsNewByItem.add(paramsNewByRecord);
				}
				if(!jylxIsSame){
					return R.error("列表信息的交易类型必须一致！");
				}
				if(errorBackByItem!=null && !"".equals(errorBackByItem)){
					return R.error(errorBackByItem);
				}
			}else {
				return R.error("列表信息为空！");
			}

		}else {
			return R.error("列表信息为空！");
		}
		//新增列表信息
		//先删除
		accountMapper.deleteAdvanceAccountReimbursementByPbid(tcwAdvanceAccountReimbursement.getBid());
		for (int i = 0; i < paramsNewByItem.size(); i++) {
			Map<String, Object> item = paramsNewByItem.get(i);
			TcwAdvanceAccountReimbursementItem tcwAdvanceAccountReimbursementItem = JSON.parseObject(JSON.toJSONString(item), TcwAdvanceAccountReimbursementItem.class);
			//新增
			tcwAdvanceAccountReimbursementItemMapper.insert(tcwAdvanceAccountReimbursementItem);
		}

		tcwAdvanceAccountReimbursementMapper.update(tcwAdvanceAccountReimbursement);
		yspTaskService.setOtherParams(tcwAdvanceAccountReimbursement.getBid(),tcwAdvanceAccountReimbursement.getRemark(),params.get("vname"));
		//return R.ok(AddDto.noAction());
		return R.ok(AddDto.gotoEdit("/web/account/tcwAdvanceAccountReimbursement/toEdit?bid=" + tcwAdvanceAccountReimbursement.getBid()));
	}


	//删除
	@Override
	@Transactional
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TcwAdvanceAccountReimbursement entity = new TcwAdvanceAccountReimbursement().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		//删除列表信息
		accountMapper.deleteAdvanceAccountReimbursementByPbid(entity.getBid());
		//删除
		tcwAdvanceAccountReimbursementMapper.deleteTrue(id);
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}


	/**
	 * 流转通过
	 */
	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {

		TcwAdvanceAccountReimbursement entity = new TcwAdvanceAccountReimbursement().setId(id).queryFirst();
		Flow f = yspTaskService.flowPass(entity.getBid(), loginUserId);
		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				flowFinish(entity.getBid());
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {

		TcwAdvanceAccountReimbursement entity = new TcwAdvanceAccountReimbursement().setBid(bid).queryFirst();
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		entity.setUpdateTime(theDate);

		BigDecimal thisTotal = BigDecimal.ZERO;
		String jylx = "";
        List<TcwAdvanceAccountReimbursementItem> itemList = new TcwAdvanceAccountReimbursementItem().setPbid(bid).queryList();
        if(itemList!=null && itemList.size()>0){
			Long userChangeId = null;
			//获取制单人信息
			TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
			if(tsUserChange!=null){
				userChangeId = tsUserChange.getId();//制单人变更信息
			}

            for(TcwAdvanceAccountReimbursementItem item:itemList){
                TcwAdvanceAccountDetail fromDetail = new TcwAdvanceAccountDetail().setId(item.getAdvanceAccountDetailId()).queryFirst();
                if(fromDetail!=null){
                    //新增台账明细
                    TcwAdvanceAccountDetail tcwAdvanceAccountDetail = new TcwAdvanceAccountDetail();
                    tcwAdvanceAccountDetail.setPid(entity.getAdvanceAccountId());
                    tcwAdvanceAccountDetail.setCreateChangeId(entity.getCreateChangeId());
                    tcwAdvanceAccountDetail.setCompanyInfoVid(entity.getCompanyVid());//所属公司vid
                    tcwAdvanceAccountDetail.setAdvanceTypeCode("YZZHLX001");//报销类型
                    tcwAdvanceAccountDetail.setVjylx(fromDetail.getVjylx());//交易类型名称
                    tcwAdvanceAccountDetail.setDetailName("预支账户报销单"+entity.getBid());//名称
                    tcwAdvanceAccountDetail.setUnitPrice(fromDetail.getTotalPrice());//充值金额
                    tcwAdvanceAccountDetail.setQuantity(new BigDecimal(1));//数量
                    tcwAdvanceAccountDetail.setTotalPrice(BigDecimal.ZERO.subtract(fromDetail.getTotalPrice()));//总额
                    tcwAdvanceAccountDetail.setRemark(entity.getRemark());//备注
                    tcwAdvanceAccountDetail.setStatus(1);
					tcwAdvanceAccountDetail.setFromId(entity.getId());
					tcwAdvanceAccountDetail.setFromType(1);
					tcwAdvanceAccountDetail.setCreateChangeId(userChangeId);
					if(fromDetail.getVgsbm()!=null)tcwAdvanceAccountDetail.setVgsbm(fromDetail.getVgsbm());
					if(fromDetail.getProxyPrice()!=null)tcwAdvanceAccountDetail.setProxyPrice(fromDetail.getProxyPrice());
					if(fromDetail.getProxyTotalPrice()!=null)tcwAdvanceAccountDetail.setProxyTotalPrice(fromDetail.getProxyTotalPrice());
					tcwAdvanceAccountDetail.setTransferStatus(1);
					//20250211,由于实际：YYBX-241112-1002,不用产生划拨流水，以及明细（被删除），所以注释掉该代码
                    //tcwAdvanceAccountDetailMapper.insert(tcwAdvanceAccountDetail);
					thisTotal = thisTotal.add(fromDetail.getTotalPrice());
					jylx = fromDetail.getVjylx();

					//产生明细对应流水
					//if(entity.getPayStatus()==1)tcwAdvanceAccountDetailService.doTransferFlow(tcwAdvanceAccountDetail.getId());
					//修改状态
					fromDetail.setDetailType(1);
					//tcwAdvanceAccountDetailMapper.update(fromDetail);
                }
            }
        }
        //PayStatus 状态为1时，才产生流水
		if(entity.getPayStatus()==1){
			//新增一条流水
			ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm(entity.getVgsbm()).queryFirst();
			TcwAdvanceAccount tcwAdvanceAccount = new TcwAdvanceAccount().setId(entity.getAdvanceAccountId()).queryFirst();
			if(thrOperateCompanyApply!=null && tcwAdvanceAccount!=null){
				//新增流水
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyWithJc(
						entity.getVgsbm(),thrOperateCompanyApply.getVgsjc(),tcwAdvanceAccount.getCode(),tcwAdvanceAccount.getName(),
						jylx, thisTotal,theDate, theDate,"预支账户报销单"+entity.getBid(),entity.getBid(),
						theDate);
			}

			//获取业务交易类型信息
			String transactionTypeStr = jylx;
			TbBaseInfo transactionTypeItem = tcwFinancialTransactionFlowService.getTransactionType(transactionTypeStr);

			//财务交易流水
			if(transactionTypeItem!=null && transactionTypeItem.getId()!=null){
				String vyhzhmc = "";
				String vkhh = "";
				String vyhzh = "";
				if(entity.getAccountType()==0){
					TsUserBankInfo tsUserBankInfo = new TsUserBankInfo().setId(entity.getUserBankInfoId()).queryFirst();
					if(tsUserBankInfo!=null && tsUserBankInfo.getVyhzhmc()!=null){
						vyhzhmc = tsUserBankInfo.getVyhzhmc();
						vkhh = tsUserBankInfo.getVkhh();
						vyhzh = tsUserBankInfo.getVyhzh();
					}else {
						throw new IllegalArgumentException("未查询到对应的银行账户名称信息");
					}
				}else {
					TcwPartnerBankInfo tcwPartnerBankInfo = new TcwPartnerBankInfo().setId(entity.getPartnerBankInfoId()).queryFirst();
					if(tcwPartnerBankInfo!=null && tcwPartnerBankInfo.getVyhzhmc()!=null){
						vyhzhmc = tcwPartnerBankInfo.getVyhzhmc();
						vkhh = tcwPartnerBankInfo.getVkhh();
						vyhzh = tcwPartnerBankInfo.getVyhzh();
					}else {
						throw new IllegalArgumentException("未查询到对应的银行账户名称信息");
					}
				}
				R res = tcwFinancialTransactionFlowService.add(true,
						entity.getCompanyBankInfoId(), transactionTypeItem.getBid(),
						vyhzhmc,vkhh, vyhzh,
						thisTotal.negate(),
						entity.getCreateTime(),theDate,new Date(),"预支账户报销单"+entity.getBid()+entity.getRemark(),
						TcwFinancialTransactionFlowEnum.FromType.TCW_AdvanceAccountReimbursementItem.value,entity.getId());
				if(res.getCode().equals( R.Code.FAILED.value)){
					throw new IllegalArgumentException(res.getMsg());
				}
			}
		}


		//修改信息
        tcwAdvanceAccountReimbursementMapper.update(entity);

	}



	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCW_AdvanceAccountReimbursement",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		/*
		if(checkUtil.isNotNullByObject(params.get("accountType")) && checkUtil.isNotNullByObject(params.get("accountTypeByModal"))){
			if(!params.get("accountType").equals(params.get("accountTypeByModal"))){
				backMsg = "收款账户性质和所选的银行账户不一致！";
			}
		}
		 */
		return backMsg;
	}



	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> entity = new TcwAdvanceAccountReimbursement()

				.addLeftJoin("TCW_AdvanceAccount AA ON AA.Id = A.AdvanceAccountId ")
				.addField("AA.Code AS code")//预支账户编码
				.addField("AA.Name AS name")//付款账户名称

				.addField("CASE " +
						"WHEN A.AccountType = 0 THEN '员工账户' " +
						"WHEN A.AccountType = 1 THEN '合作商账户' " +
						" ELSE '' END accountTypeTxt")

				/*
                .addLeftJoin("TS_UserBankInfo UB ON AA.UserBankInfoId = UB.Id")
                        .addLeftJoin("TS_UserInfo B on  B.UserId = UB.UserId")
                        .addField("B.DeptName AS deptName")//账户管理部门
                */
				.addLeftJoin("TS_OrganizationInfo O ON AA.Orgid = O.Orgid ")
				.addField("O.OrgName AS orgName")//账户管理部门

				//列表
				.addLeftJoin("(SELECT I.Pbid,SUM ( D.TotalPrice ) AS totalPriceByThis FROM TCW_AdvanceAccountReimbursementItem I LEFT JOIN TCW_AdvanceAccountDetail D ON I.AdvanceAccountDetailId = D.Id GROUP BY I.Pbid) D1 on D1.Pbid = A.Bid")
				.addField("ISNULL(D1.totalPriceByThis, 0) AS totalPriceByThis")//本次报销金额

				//明细2
				.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceByOther FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode NOT IN ('YZZHLX000','YZZHLX001') GROUP BY Pid) D2 on D2.Pid = A.AdvanceAccountId AND 1=1")
				.addField("ISNULL(D2.totalPriceByOther, 0) AS totalPriceByOther")//台账总金额
				//明细3
				.addLeftJoin("(SELECT Pid, SUM(TotalPrice) AS totalPriceBySubmit FROM TCW_AdvanceAccountDetail  WHERE AdvanceTypeCode ='YZZHLX001' GROUP BY Pid) D3 on D3.Pid = A.AdvanceAccountId AND 1=1")
				.addField("ISNULL(D3.totalPriceBySubmit, 0) AS totalPriceBySubmit")//台账报销金额,字段“总额”之和（预支类型为报销）


				/*
        .addLeftJoin("TS_UserBankInfo UB2 ON A.UserBankInfoId = UB2.Id")
                .addField("UB2.Vyhzhmc AS vyhzhmc")//收款银行账户名称
                .addField("UB2.Vkhh AS vkhh")//收款开户行
                .addField("UB2.Vyhzh AS vyhzh")//收款银行账户编码

                 */
				.addLeftJoin("TS_UserBankInfo UB ON A.UserBankInfoId = UB.Id AND A.AccountType=0")
				.addLeftJoin("TCW_PartnerBankInfo PB ON A.PartnerBankInfoId = PB.Id AND A.AccountType=1")
				.addField("CASE WHEN A.AccountType=0 THEN UB.Vyhzhmc ELSE PB.Vyhzhmc END _ys_vyhzhmc")//收款银行账户名称
				.addField("CASE WHEN A.AccountType=0 THEN UB.Vkhh ELSE PB.Vkhh END _ys_vkhh")//收款开户行
				.addField("CASE WHEN A.AccountType=0 THEN UB.Vyhzh ELSE PB.Vyhzh END _ys_vyhzh")//收款银行账户编码

				.addLeftJoin("TB_CompanyInfo CI ON CI.Vid = A.CompanyVid ")
				.addField("CI.Vname AS vname")//所属公司

				.addLeftJoin("(SELECT ISNULL(SUM(TAD.UnitPrice),0)AS unitPrice,TAI.Pbid from TCW_AdvanceAccountReimbursementItem TAI " +
						"LEFT JOIN TCW_AdvanceAccountDetail TAD ON TAD.id=TAI.AdvanceAccountDetailId " +
						"GROUP BY TAI.Pbid ) B ON B.Pbid =A.Bid ")
				.addField("B.UnitPrice AS paymentAmountTotal")//付款总金额

				.addLeftJoin("THR_OperateCompanyApply C ON C.Vgsbm = A.Vgsbm ")
				.addField("C.Vgsjc AS vgsjc")//运营公司简称

				.addLeftJoin("TB_CompanyBankInfo CB ON A.CompanyBankInfoId = CB.Id")
				.addField("CB.Vyhzhmc AS pvyhzhmc")//付款银行账户名称
				.addField("CB.Vkhh AS pvkhh")//付款开户行
				.addField("CB.Vyhzh AS pvyhzh")//付款银行账户编码

				.setBid(bid)
				.queryFirstMap();
		//获取审核时间
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.get("bid").toString()).queryFirst();
		if(ysProcInst!=null && ysProcInst.getUpdateTime()!=null)entity.put("auditingTime", DateUtil.getYYYY_MM_DD_HH_mm_ss(ysProcInst.getUpdateTime()));

		return entity;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> itemList = new TcwAdvanceAccountDetail()
				.addLeftJoin("TCW_AdvanceAccount P ON P.Id = A.Pid")//预支账户管理
				.addField("P.Code AS pCode")//预支账户编码
				.addField("P.Name AS pName")//预支账户名称

				.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId")//人员变动信息
				.addField("U.UserName AS userName")//新增人员
				.addField("U.DeptName AS deptName")//新增部门

				.addLeftJoin("TB_AdvanceType T ON T.Code = A.AdvanceTypeCode")//预支类型
				.addField("T.Name AS advanceTypeName")//预支类型名称

				.addLeftJoin("TB_CompanyInfo C ON C.Vid = A.CompanyInfoVid")//公司信息表
				.addField("C.Vname AS companyName")//公司名称

				.addLeftJoin("TCW_AdvanceAccountReimbursementItem AR ON AR.AdvanceAccountDetailId = A.Id")//预支账户报销单列表
				.addField("AR.Id AS reimbursementItemId")//id
				.addField("AR.Pbid AS reimbursementItemPbid")//父表Bid
				.addField("AR.AdvanceAccountDetailId AS advanceAccountDetailId")//预支账户管理明细表id

				.where("AR.Pbid = '"+bid+"'")
				.queryMap();
		return itemList;
	}




}
